<template>
  <div class="app-container">
    <div class="filter-container">
      <el-form :inline="true" class="demo-form-inline" label-position="left" label-width="70px">
        <el-form-item label="目标" label-width="50px">
          <el-input v-model="search.mainName" placeholder="请输入目标" />
        </el-form-item>
        <el-form-item label="执行人" label-width="60px">
          <el-select v-model="search.executor" filterable remote placeholder="请输入执行人" :remote-method="remoteMethod"
            clearable :loading="loading">
            <el-option v-for="item in options" :key="item.userName" :label="`${item.acName}(${item.cityName})`"
              :value="item.userName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="目标状态">
          <el-select v-model="search.taskState" placeholder="请选择" clearable>
            <el-option v-for="item, i in typeOptions" :key="i" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="科室" label-width="45px">
          <el-select v-model="search.deptName" placeholder="请选择" clearable>
            <el-option v-for="item, i in ksList" :key="i" :label="item.label" :value="item.label" />
          </el-select>
        </el-form-item> -->
        <el-form-item label="科室" prop="deptName" label-width="45px">
          <tree-select :data="treeSelectData" :defaultProps="treeDefaultProps" :nodeKey="treeNodeKey"
            :checkedKeys="treeDefaultCheckedKeys" :isAddState='isAddState' @popoverHide="popoverHide"></tree-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onSubmit">查询</el-button>
          <el-button @click="reset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-button type="primary" @click="handleaddTask">新增目标</el-button>
    <el-table :data="rolesList" style="width: 100%;margin-top:16px;" border class="table-box" :height="height + 'px'"
      v-loading="loadTable">
      <el-table-column align="center" label="序号" width="60">
        <template slot-scope="scope">
          {{ (pagination.pageNum - 1) * pagination.pageSize + scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="目标" width="300">
        <template slot-scope="scope">
          {{ scope.row.mainName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="科室">
        <template slot-scope="scope">
          {{ scope.row.deptName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="制定人" width="90">
        <template slot-scope="scope">
          {{ scope.row.distributorAcName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="执行人" width="90">
        <template slot-scope="scope">
          {{ scope.row.executorAcName }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="归属组织">
        <template slot-scope="scope">
          {{ scope.row.belonging }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="计划开始时间">
        <template slot-scope="scope">
          {{ scope.row.planBeginTime || "--" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="计划结束时间">
        <template slot-scope="scope">
          {{ scope.row.planEndTime || "--" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="实际完成时间">
        <template slot-scope="scope">
          {{ scope.row.actualFinishTime || "--" }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="关键结果" width="80">
        <template slot-scope="scope">
          {{ scope.row.subtaskCount || 0 }}
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="自评分" width="80">
        <template slot-scope="scope">
          {{ scope.row.taskProgress ? truncateToFixed(scope.row.taskProgress, 2) : 0 }}
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="时间进度" width="80">
        <template slot-scope="scope">
          {{ scope.row.timeProgress ? truncateToFixed(scope.row.timeProgress, 1) : 0 }}%
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="落实情况" width="80">
        <template slot-scope="scope">
          <span :style="{ color: getColor(scope.row.taskImplementation) }">{{ scope.row.taskImplementation }}</span>
        </template>
      </el-table-column> -->
      <el-table-column align="center" label="状态" width="70">
        <template slot-scope="scope">
          <span :style="{ color: getColor(scope.row.taskState) }">{{ getStateName(scope.row.taskState) }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="140">
        <template slot-scope="scope">
          <el-button type="text" @click="handleOk(scope)" v-if="scope.row.taskState != 2">完成目标</el-button>
          <el-button type="text" @click="goDetail(scope)">详情</el-button>
          <el-button type="text" @click="handleEdit(scope)" v-if="scope.row.taskState != 2">编辑</el-button>
          <el-button type="text" @click="handleDelete(scope)" v-if="scope.row.taskState != 2">终止</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total > 0" :total="total" :page.sync="pagination.pageNum" :limit.sync="pagination.pageSize"
      @pagination="getPagination" />
    <!-- <el-dialog :visible.sync="dialogVisible" title="目标认领" :close-on-click-modal="false"
      width="70%">
      <addDialog />
      <div style="text-align:right;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog> -->
    <el-dialog :visible.sync="dialogVisible" :title="dialogType === 'edit' ? '编辑' : '新增'" :close-on-click-modal="false">
      <el-form :model="role" label-width="110px" label-position="left" :rules="rules" ref="ruleForm">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="目标" prop="mainName">
              <el-select v-model="role.mainName" filterable placeholder="请选择目标" popper-class="popperClass" clearable>
                <el-option v-for="item, i in childrenList" :key="i" :label="`${i + 1}.${item.subName}`"
                  :value="item.subName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="科室" prop="deptName">
              <tree-select :data="treeSelectData" :defaultProps="treeDefaultProps" :nodeKey="treeNodeKey" :width="810"
                :checkedKeys="treeDefaultCheckedKeysAdd" :isAddState='isAddState' @popoverHide="popoverHideAdd"></tree-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="24">
            <el-form-item label="科室" prop="deptName">
              <el-select v-model="role.deptName" filterable placeholder="请选择科室" popper-class="popperClass" clearable>
                <el-option v-for="item in ksList" :key="item.label" :label="item.label" :value="item.label">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :span="24">
            <el-form-item label="执行人" prop="executor">
              <el-select v-model="role.executor" filterable remote placeholder="请输入执行人" :remote-method="remoteMethod"
                :loading="loading">
                <el-option v-for="item in options" :key="item.userName" :label="`${item.acName}(${item.cityName})`"
                  :value="item.userName">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="计划开始时间" prop="planBeginTime">
              <el-date-picker v-model="role.planBeginTime" type="date" placeholder="选择日期" format="yyyy-MM-dd"
                value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="计划结束时间" prop="planEndTime">
              <el-date-picker v-model="role.planEndTime" type="date" placeholder="选择日期" format="yyyy-MM-dd"
                value-format="yyyy-MM-dd" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align:right;">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import path from 'path'
import { getTaskList, addTask, deleteTask, updateTask, completeTask, getPersonList, getChildrenMb } from '@/api/api'
import Pagination from '@/components/Pagination'
import addDialog from './components/addDialog.vue'
import treeSelect from '@/components/treeSelect'
const defaultRole = {}
let orgs = [...orgList]
let orgIndex = orgs.findIndex(item => item.label === '所有科室')
if (orgIndex > -1) {
  orgs.splice(orgIndex, 1)
}
let org = orgs
export default {
  name: 'work',
  components: { Pagination, addDialog, treeSelect },
  data() {
    return {
      treeSelectData: orgTreeList,
      treeDefaultProps: {
        children: 'children',
        label: 'label'
      },
      treeNodeKey: 'value',
      treeDefaultCheckedKeys: [],
      treeDefaultCheckedKeysAdd: [],
      isAddState: '1',
      childrenList: [],
      ksList: org,
      rowTaskState: 0,
      rules: {
        mainName: [
          { required: true, message: '请输入目标', trigger: 'change' }
        ],
        executor: [
          { required: true, message: '请选择执行人', trigger: 'change' }
        ],
        planBeginTime: [
          { required: true, message: '请选择计划开始时间', trigger: 'change' }
        ],
        planEndTime: [
          { required: true, message: '请选择计划结束时间', trigger: 'change' }
        ],
        deptName: [
          { required: true, message: '请选择科室', trigger: 'change' }
        ],
      },
      loading: false,
      loadTable: false,
      height: 400,
      typeOptions: [
        {
          value: 0,
          label: '待开始'
        },
        {
          value: 1,
          label: '进行中'
        },
        {
          value: 2,
          label: '已完成'
        }, {
          value: 3,
          label: '已延期'
        }
      ],
      changetypeOptions: [
        {
          value: 0,
          label: '待开始'
        },
        {
          value: 1,
          label: '进行中'
        },
      ],
      options: [],
      total: 0,
      role: Object.assign({}, defaultRole),
      routes: [],
      rolesList: [],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      search: { executor: '' },
      pfOptions: [],
      zxOptions: [],
      pagination: {
        'pageNum': 1,
        'pageSize': 20
      },
      time: null
    }
  },
  watch: {
    dialogVisible(val) {
      if (!val) {
        this.role = {}
        this.options = []
        this.treeDefaultCheckedKeysAdd = []
        this.$refs['ruleForm'].resetFields();
      }
    }
  },
  beforeRouteEnter(to, from, next) {
    next(vm => {
      if (to.path == '/work/list') {
        vm.onSubmit();
      }
    });
  },
  computed: {
    routesData() {
      return this.routes
    }
  },
  created() {
    this.getTasks();
    this.height = this.getHeight();
    let that = this;
    window.onresize = function (event) {
      that.height = that.getHeight();
    };
  },
  methods: {
    popoverHide(checkedIds, checkedData) {
      this.search = { ...this.search, deptName: checkedIds }
    }, 
    popoverHideAdd(checkedIds, checkedData) {
      this.role = { ...this.role, deptName: checkedIds }
    },
    // 目标查询
    changeMainName(subName) {
      if (this.time) {
        clearTimeout(this.time)
      }
      let that = this
      this.time = setTimeout(() => {
        that.getChildren(subName, true)
      }, 500)
    },
    // 选择目标
    choiceMb(item) {
      this.role = { ...this.role, mainName: item.subName }
      // this.$refs.mainNameRef.blur()
      this.$refs.popover.doClose();
    },
    getChildren(subName, isFlag) {
      getChildrenMb({ taskType: '10', subName }).then(res => {
        let cityName = localStorage.getItem('cityName')
        this.childrenList = res.filter(item => item.subBelongings.indexOf(cityName) > -1) || []
        // if (subName && !res.length) {
        //   this.$refs.popover.doClose();
        // } else if (res.length && isFlag) {
        //   this.$refs.popover.doShow()
        // }
      })
    },
    getPerson(acName) {
      this.loading = false;
      getPersonList({ acName }).then(res => {
        this.options = res || []
      })
    },
    getHeight() {
      let winHieght = window.innerHeight;
      return winHieght - 280;
    },
    getStateName(state) {
      let find = this.typeOptions.find(item => item.value == state)
      return find?.label || state || ''
    },
    onSubmit() {
      this.pagination = {
        "pageNum": 1,
        "pageSize": 20
      }
      this.getTasks()
    },
    reset() {
      this.search = { executor: '' }
      this.treeDefaultCheckedKeys = []
      this.onSubmit()
    },
    remoteMethod(query) {
      if (query !== '') {
        this.loading = true;
        this.getPerson(query.toLowerCase())
      } else {
        this.options = [];
      }
    },
    getPagination(pagination) {
      this.pagination = pagination
      this.getTasks()
    },
    getColor(state) {
      let taskState = this.getStateName(state)
      const colors = {
        '超前': '#1ecd00',
        '正常': '#1ecd00',
        '已完成': '#1ecd00',
        '进行中': '#1890ff',
        '待开始': '#999',
        '已延期': '#ff4949',
        '落后': '#ff4949'
      }
      return colors[taskState]
    },
    truncateToFixed(value, decimals) {
      const integerPart = Math.trunc(value || 0); // 获取整数部分
      const decimalPart = value - integerPart; // 获取小数部分
      const factor = Math.pow(10, decimals);
      const truncatedDecimalPart = decimalPart < 0 ? Math.ceil(decimalPart * factor) / factor : Math.floor(decimalPart * factor) / factor; // 根据正负选择向上或向下截断
      return integerPart + truncatedDecimalPart; // 组合整数部分和小数部分
    },
    goDetail(scope) {
      this.$router.push({
        path: `/work/detail/${scope.row.mainId}`
      })
    },
    async getTasks() {
      this.loadTable = true
      try {
        const res = await getTaskList({ page: this.pagination.pageNum, size: this.pagination.pageSize, ...this.search, distributor: localStorage.getItem('userName'), taskType: '20' });
        this.total = res.data.total || 0;
        this.rolesList = res?.data?.data || [];
        this.loadTable = false
      } catch (e) {
        this.loadTable = false
      }
    },

    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden) { continue }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title
        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    handleaddTask() {
      this.getChildren()
      this.role = Object.assign({}, defaultRole)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = 'new'
      this.dialogVisible = true
    },
    async handleEdit(scope) {
      await this.getPerson(scope.row.executorAcName)
      await this.getEdit(scope)
    },
    getEdit(scope) {
      this.getChildren()
      this.rowTaskState = scope.row.taskState
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      this.treeDefaultCheckedKeysAdd = [scope.row.deptName]
      this.role = { ...scope.row }
    },
    handleOk({ $index, row }) {
      this.$confirm('确认当前目标已完成?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          completeTask(row.mainId).then(res => {
            this.$message({
              type: res.message === '目标已完成' ? 'success' : 'warning',
              message: res.message
            })
            this.getTasks();
          })
        })
        .catch(err => { console.error(err) })
    },
    handleDelete({ $index, row }) {
      this.$confirm('确认终止当前目标?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          deleteTask(row.mainId).then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getTasks();
            } else {
              this.$message({
                type: 'warning',
                message: res.message
              })
              this.getTasks();
            }
          })
        })
        .catch(err => { console.error(err) })
    },
    generateTree(routes, basePath = '/', checkedKeys) {
      const res = []

      for (const route of routes) {
        const routePath = path.resolve(basePath, route.path)

        // recursive child routes
        if (route.children) {
          route.children = this.generateTree(route.children, routePath, checkedKeys)
        }

        if (checkedKeys.includes(routePath) || (route.children && route.children.length >= 1)) {
          res.push(route)
        }
      }
      return res
    },
    confirmRole() {
      this.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          if (this.role.planBeginTime <= this.role.planEndTime) {
            const isEdit = this.dialogType === 'edit'
            let phone = this.options.find(item => item.userName === this.role.executor)?.phone
            if (isEdit) {
              updateTask({ ...this.role, distributor: localStorage.getItem('userName'), phone, mainDescription: '' }, this.role.mainId).then(res => {
                this.dialogVisible = false
                this.getTasks()
                this.options = []
              })
            } else {
              addTask({ ...this.role, distributor: localStorage.getItem('userName'), phone, mainDescription: '', taskType: '20' }).then(res => {
                this.dialogVisible = false
                this.getTasks()
                this.options = []
              })
            }
          } else {
            this.$message({
              type: 'warning',
              message: '计划结束时间需晚于计划开始时间!'
            })
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  overflow-y: auto;
  height: calc(100vh - 86px);
  padding: 16px 20px 0;

  .roles-table {
    margin-top: 30px;
  }

  .permission-tree {
    margin-bottom: 30px;
  }
}


.filter-container {
  ::v-deep .el-form-item {
    margin-bottom: 0;
  }
}

::v-deep .el-select,
::v-deep .el-date-editor.el-input,
::v-deep .el-date-editor.el-input__inner {
  width: 100%;
}

.table-box {
  ::v-deep .el-button--medium {
    padding: 0px 5px;
  }
}

.popover-list {
  min-height: 30px;
  line-height: 30px;
  cursor: pointer;
  padding: 0 10px;
  overflow: hidden;
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;

  &:hover {
    background: #f3f6fb;
  }
}
</style>
<style>
.popper-list {
  padding: 0;
}

.popperClass {
  width: 500px;
}
</style>